import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 07 - 18
 * Time: 15:41
 */
//力扣107. 二叉树的层序遍历 II
public class Solution5 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();//顺序表里面的每个元素又是一个顺序表
        if(root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();//链表实现队列
        queue.offer(root);
        while(!queue.isEmpty()) {
            int size = queue.size();//计算某一层一共有多少个节点
            List<Integer> tmp = new ArrayList<>();
            while(size != 0) {
                TreeNode cur = queue.poll();
                tmp.add(cur.val);
                size--;
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            ret.add(tmp);
        }
        List<List<Integer>> ret1 = new ArrayList<>();//或者用Collections.reverse(ret)
        for(int i = ret.size() - 1; i >= 0; i--) {
            ret1.add(ret.get(i));
        }
        return ret1;
    }
}
